<template>
    <n-space>
        <n-form ref="formRef" class="pt-50px pl-50px w-500px" :model="pwForm" :rules="rules" labn-width="120" label-placement="left">
        <n-form-item label="原密码:" path="oldPwd" >
            <n-input type="password" v-model:value="pwForm.oldPw" placeholder="请输入原密码" clearable/>
        </n-form-item>
        <n-form-item label="新密码:" path="pwd" >
            <n-input type="password" v-model:value="pwForm.pwd" placeholder="请输入新密码" clearable/>
        </n-form-item>
        <n-form-item label="确认密码:" path="confirmPwd" >
            <n-input type="password" v-model:value="pwForm.confirmPwd" placeholder="确认密码" clearable/>
        </n-form-item>
        <n-form-item>
            <n-button attr-type="button" type="primary" class="ml-auto mr-auto" @click="handleSubmit">
                提交
            </n-button>
        </n-form-item>
    </n-form>
    </n-space>

</template>

<script  setup lang='ts' >
import { ref, reactive,toRefs } from "vue"
import { FormInst } from 'naive-ui'
import { useFormRules } from '@/hooks/common/form';
import { fetchUpdatePW } from '@/service/api/auth'
import {  useAuthStore } from '@/store/modules/auth'

interface ChangePwObj { oldPw: string , pwd: string , confirmPwd: string  }

const auth = useAuthStore()
const formRef = ref<FormInst | null>(null)
const pwForm = reactive<ChangePwObj>({ oldPw: "", pwd: "", confirmPwd: "" })
const {formRules,createConfirmPwdRule} = useFormRules()
const rules = {
    oldPw:{required: true, message: "请输入原密码", trigger: 'blur'},
    pwd: formRules.pwd,
    confirmPwd: createConfirmPwdRule(toRefs(pwForm).pwd)
}

function handleSubmit(){
    formRef.value?.validate(async e => {
        if (!e) {
         const {error} = await fetchUpdatePW(pwForm)
				if(!error){
					window.$message?.success("操作成功，请重新登录")
					auth.logout()
				 }
        }
    }).catch()
}
</script>

<style lang='scss' scoped>
.show_pwd {
    cursor: pointer;
    user-select: none;
    padding-right: 5px;
}

</style>
